<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\BaseController;
use app\middleware\AdminAuth;
use app\model\Admin;
use app\model\Cdkey;
use app\model\Config;
use app\model\Invite;
use app\model\Notice;
use app\model\Profit;
use app\model\Task;
use app\model\Transfer;
use app\model\TransferList;
use app\model\User;
use app\model\Version;
use app\validate\UserReg;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Session;
use think\facade\View;
use think\Request;
use think\Response;

use app\model\Phonecharge;
use app\model\PhonechargeList;
use app\model\UserAuth;
use think\facade\Filesystem;

class Main extends BaseController
{
    protected $middleware = [
        AdminAuth::class
    ];

    public function index()
    {
        return view();
    }
    
    /**
     * 联系我们
     */
    public function contactus()
    {
        
        if ($this->request->isPost()) {
            // $id = $this->request->param('id');
            $data = $this->request->param();
            $ret = Notice::update($data, ['id' => 3]);
            if ($ret) {
                return json(['code' => 200, 'msg' => '修改成功']);
            }
            return json(['code' => -1, 'msg' => '修改失败']);
        }
        
        $info = Db::name('notice')->where('id', 3)->find();
        View::assign('info', $info);
        return View::fetch();
    }

    /**
     * 用户审核
     */
    public function auditUser() {
        if(!$this->request->isPost()) {
            return json(['code'=>400,'msg'=>'请求方式错误']);
        }

        $id = input("post.id");
        if(!$id) {
            return json(['code'=>400,'msg'=>'参数错误']);
        }
        
        $status = input("post.status");
        if(!in_array($status, [1,2])) {
            return json(['code'=>400,'msg'=>'审核状态错误']);
        }
        $reason = input('post.reason');
        
        $userAuth = UserAuth::find($id);
        if(!$userAuth) {
            return json(['code'=>400,'msg'=>'实名认证信息不存在']);
        }
        if($userAuth->status > 0) {
            return json(['code'=>400,'msg'=>'该用户已审核, 无需重复审核']);
        }

        UserAuth::where("id", $id)->update([
            "status"=>$status, 
            "reason"=>$reason,
            "reviewed_by" => 0,
            "reviewed_at" => date("Y-m-d H:i:s"),
            "update_at" => date("Y-m-d H:i:s")
        ]);

        return json(['code'=>200,'msg'=>'操作成功']);
    }
    
    
    public function delUser()
    {
        if(!$this->request->isPost()) {
            return json(["code"=>400, "msg"=>"错误的请求方式"]);      
        }
        
        $id = input("post.id");
        if(!$id) {
            return json(['code'=>400,'msg'=>'参数错误']);
        }
        
        UserAuth::where("id", $id)->delete();
        
        return json(['code'=>200,'msg'=>'操作成功']);
    }

    /**
     * 实名审核
     */
    public function userAuth() {
        if($this->request->isPost()) {
            // 分页处理
            $page = $this->request->param("page", 1, 'intval');
            if($page < 1) {
                $page = 1;
            }
            $limit = $this->request->param("limit", 10, 'intval');
            $start = $limit * ($page - 1);
            
            // 查询条件
            $where = [];
            if($tel = input("post.tel", "", "trim")) {
                $where[] = ['u.tel', '=', $tel];
            }
            if($username = input("post.username", "", "trim")) {
                $where[] = ['u.username', 'like', '%' . $username . '%'];
            }
            $status = input("post.status");
            if($status === 0 || in_array($status,  [1, 2])) {
                $where[] = ['ua.status', '=', $status];
            }
            if($realName = input("post.real_name", "", "trim")) {
                $where[] = ['ua.real_name', 'like', '%' . $realName . '%'];
            }
            
            $list = UserAuth::alias("ua")->leftJoin("user u", "u.id = ua.user_id")
                ->field("ua.*, u.username, u.avatar, u.tel")
                ->where($where)->limit($start, $limit)->order("ua.id", "desc")->select();
            return json(['data' => $list, "code"=>0, "where"=>$where]);        
        }
        return view('main/user_auth/index');
    }

    /**
     * 上传文件
     */
    public function uploadFile() {
        $formField = "file";
        // if(!$this->request->hasFile($formField)) {
            // return json(['code'=>400,'msg'=>'上传文件不存在']);
        // }

        $file = $this->request->file($formField);
        if(!$file->isValid()) {
            return json(['code'=>400,'msg'=>'文件上传失败']);
        }
        
        $ext = $file->getExtension() ?: 'jpg';
        $newFileName = date('YmdHis') . '_' . uniqid() . '.' . $ext;
        $disk = Filesystem::disk('public');
        $filePath = $disk->putFileAs('uploads', $file, $newFileName);

        $url = $disk->url($filePath);
        return json(['code'=>200,'msg'=>'文件上传成功','data'=>['url'=>$url]]);
    }

    /**
     * 一键生成用户
     */
    public function generateUser() {
        
        $countryCode = input("post.country_code", ''); 
        $total = input("post.total", 0, 'intval');
        if(!is_int($total) || $total <= 0) {
            return json(['code' => -1, 'msg' => '请输入正确的数量']);
        }
        
        $codes = [
            '+1', // 美国
            '+44', // 英国
            '+852', // 香港
            '+81', // 日本
            '+33', // 法国
            '+86', // 中国
            '+39', // 意大利
            '+65', // 新加坡
            '+60', // 马来西亚
        ];
        if($countryCode && !in_array($countryCode, $codes)) {
            return json(['code' => -1, 'msg' => '不在选择的国家代码内!']);
        }
        
        try {
            $insertData = [];
            
            
            foreach(range(1, $total) as $i) {

                $countryCode = empty($countryCode) ? getCountryCode() : $countryCode;
                $accountName = "用户".randomStr(6);
                $password = '123456';
                $insertData[] = [
                    'country_code' => $countryCode,
                    'username' => getPhoneNumber(), // 账号
                    'password' => md5($password), // 密码
                    'password_original' => $password,
                    'out_time' => date("Y-m-d H:i:s", strtotime('+100 day')), // 到期时间
                    'balance' => 0, // 账户余额
                    'vip' => 0, // 0=普通 1=vip
                    'nickname' => $accountName, // 昵称
                    'name' => "", // 支付宝名字
                    'alipay' => "", // 支付宝账号
                    'wechat' => "", // 微信号
                    'invite' => "", // 上级邀请id
                    'remarks' => "", // 备注
                    'reg_time' => date("Y-m-d H:i:s"), // 
                    'cdkey' => "", // 绑定的卡密
                    'token' => "", // 邀请用户时的邀请码
                    'account_changed_times' => "", // alipay账号修改次数
                    'status' => "", // 状态
                    'tel' => "", // 手机号
                    'invite_status' => 0, // 是否允许邀请： 0-不可以 1-可以
                    'avatar' => "/static/assets/images/head.jpg", // 头像
                    'verify_code' => randomStr(6), // 验证码
                ];
            }

            $userModel = new User;
            $userModel->saveAll($insertData);

            return json(['code' => 200, 'msg' => '生成成功']);
        } catch (\Throwable $th) {
            return json(['code' => -1, 'msg' => '操作失败', "real_msg"=>$th->getMessage()]);
        }
    }

    /**
     * 控制台
     */
    public function console()
    {
        $userNumber = User::count();
        $cdkeyNumber = Cdkey::count();
        $transferNumber = Transfer::count();
        $sendNumber = Transfer::where('transfer_status', 2)->sum('price');
        View::assign('user', $userNumber);
        View::assign('cdkey', $cdkeyNumber);
        View::assign('transfer', $transferNumber);
        View::assign('send', $sendNumber);

        return view();
    }

    /**
     * 用户管理
     */
    public function user()
    {
        return view();
    }

    /**
     * 用户列表
     */
    public function userList()
    {
        // 分页
        $page = input('get.page', 1, 'intval');
        $limit = input('get.limit', 10, 'intval');
        $start = $limit * ($page - 1);

        $where = [];
        // 搜索条件判断
        $s_link_name = $this->request->param("search");
        if ($s_link_name != "") {
            $where[] = [
                "id|username|name", "=", $s_link_name,
            ];
        }

        // 搜索条件判断结束
        $total = User::where($where)->count();
        $list = User::where($where)->limit($start, $limit)->order("id", "desc")->select();

        // 查询用户总提现金额
        $userIds = array_column($list->toArray(), 'id');
        $totalAmounts = Transfer::whereIn('uid', $userIds)
            ->where('transfer_status', 2)
            ->field('uid, sum(price) as total')
            ->group('uid')
            ->select()
            ->toArray();
        
        $totalAmountsMap = [];
        foreach ($totalAmounts as $item) {
            $totalAmountsMap[$item['uid']] = $item['total'];
        }

        foreach ($list as $k => &$v) {
            $v['total'] = $totalAmounts[$v['id']] ?? 0;
        }

        return json([
            'code' => 0,
            'msg' => 'ok',
            'count' => $total,
            'data' => $list
        ]);
    }

    /**
     *  删除用户
     */
    public function userDel()
    {
        $id = $this->request->param("id");
        if (empty($id)) {
            $idsTxt = $this->request->param('ids');
            $ret = User::dels($idsTxt);
            if ($ret) {
                return json(['code' => 200, 'msg' => '删除成功']);
            }
            return json(['code' => -1, 'msg' => '删除失败']);
        } else {
            $ret = User::del($id);
            if ($ret) {
                return json(['code' => 200, 'msg' => '删除成功']);
            }
            return json(['code' => -1, 'msg' => '删除失败']);
        }
    }

    /**
     * 添加用户
     */
    public function userAdd()
    {
        $data = $this->request->param();
        // 校验数据
        try {
            validate(UserReg::class)->check($data);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return json(['code' => -1, 'msg' => $e->getError()]);
        }
        
        if($data['password_original']) {
            $data['password'] = md5($data['password_original']);
        }
        // 邀请码
        if(!isset($data['invite_status'])) {
            $data['invite_status'] = 0;
        }
        $data['invite_code'] = $data['invite_status'] == 1 ? randomStr() : '';
        
        $ret = User::create($data);
        if ($ret) {
            return json(['code' => 200, 'msg' => '添加成功']);
        }
        return json(['code' => -1, 'msg' => '添加失败']);
    }

    /**
     * 修改用户
     */
    public function userEdit()
    {
        $id = $this->request->param('id');
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $oldData = User::where('id', $id)->find();
            unset($data['id']);
            // 检测密码是否与之前一直 如变化则修改
            
            if ($data['password_original'] != $oldData['password_original']) {
                $data['password'] = md5($data['password_original']);
            }

            // 邀请码
            if(!isset($data['invite_status'])) {
                $data['invite_status'] = 0;
            }
            $data['invite_code'] = $data['invite_status'] == 1 ? randomStr() : '';

            $ret = User::update($data, ['id' => $id]);

            $update_data['remarks'] = $data['remarks'];
            Transfer::where('uid', $id)->update($update_data);

            if ($ret) {
                return json(['code' => 200, 'msg' => '修改成功']);
            }
            return json(['code' => -1, 'msg' => '修改失败']);
        }
    }


    /*
     * 修改状态
     */
    public function userStatus()
    {
        $id = $this->request->param('id');
        $status = $this->request->param('status');
        $ret = User::update(['status' => $status], ['id' => $id]);
        if ($ret) {
            return json(['code' => 200, 'msg' => '修改成功']);
        }
        return json(['code' => -1, 'msg' => '修改失败']);
    }

    /**
     * 卡密管理
     */
    public function cdkey()
    {
        return view();
    }

    /**
     * 卡密列表
     */
    public function cdkeyList()
    {
        $page = $this->request->param("page") ? $this->request->param("page") : 1;
        $page = intval($page);
        $limit = $this->request->param("limit") ? $this->request->param("limit") : 1;
        $limit = intval($limit);
        $start = $limit * ($page - 1);
        $where = [];
        // 搜索条件判断
        $s_link_name = $this->request->param("key");
        if ($s_link_name != "") {
            $where[] = [
                "key", "=", $s_link_name,
            ];
        }
        // 搜索条件判断结束
        $result['code'] = 0;
        $result['msg'] = '';
        $result['count'] = Cdkey::count();
        $list = Cdkey::where($where)->limit($start, $limit)->order('id desc')->select();
        $result['data'] = $list;
        return json($result);
    }

    /**
     * 生成卡密
     */
    public function buildKeys()
    {
        return view();
    }

    /**
     * 添加卡密
     */
    public function cdkeyAdd()
    {
        $data = $this->request->param();
        // 分割卡密数据
        $keys = explode(",", $data['keys']);
        $time = $data['time'];
        $remark = $data['remarks'];
        $ok = 0;
        foreach ($keys as $key) {
            if (empty($key)) {
                continue;
            }
            $info = Cdkey::where('key', $key)->find();
            if ($info) {
                continue;
            }
            $cdkey = [
                'key' => $key,
                'time' => $time,
                'remarks' => $remark,
            ];
            $ret = Cdkey::create($cdkey);
            if ($ret) {
                $ok = $ok + 1;
            }
        }
        return json(['code' => 200, 'msg' => '成功生成' . $ok . '个卡密']);
    }

    /**
     * 修改卡密
     */
    public function cdkeyEdit()
    {
        $id = $this->request->param('id');
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $ret = Cdkey::update($data, ['id' => $id]);
            if ($ret) {
                return json(['code' => 200, 'msg' => '修改成功']);
            }
            return json(['code' => -1, 'msg' => '修改失败']);
        }
    }

    /**
     * 删除卡密
     */
    public function cdkeyDel()
    {
        $id = $this->request->param("id");
        if (empty($id)) {
            $idsTxt = $this->request->param('ids');
            $ret = Cdkey::dels($idsTxt);
            if ($ret) {
                return json(['code' => 200, 'msg' => '删除成功']);
            }
            return json(['code' => -1, 'msg' => '删除失败']);
        } else {
            $ret = Cdkey::del($id);
            if ($ret) {
                return json(['code' => 200, 'msg' => '删除成功']);
            }
            return json(['code' => -1, 'msg' => '删除失败']);
        }
    }

    /**
     * 提现管理
     */
    public function transfer()
    {
        return view();
    }

    /**
     * 提现列表
     */
    // public function transferList()
    // {
    //     $page = $this->request->param("page") ? $this->request->param("page") : 1;
    //     $page = intval($page);
    //     $limit = $this->request->param("limit") ? $this->request->param("limit") : 1;
    //     $limit = intval($limit);
    //     $start = $limit * ($page - 1);
    //     $where = [];
    //     // 搜索条件判断
    //     $s_link_name = $this->request->param("key");
    //     if ($s_link_name != "") {
    //         $where[] = [
    //             "username|account", "=", $s_link_name,
    //         ];
    //     }
    //     $searchType = $this->request->param("type");
    //     if ($searchType != 'all' && $searchType != '') {
    //         $where[] = [
    //             'transfer_status', '=', $searchType
    //         ];
    //     }
    //     // 搜索条件判断结束
    //     $result['code'] = 0;
    //     $result['msg'] = '';
    //     $result['count'] = Transfer::count();
    //     $list = Transfer::where($where)->limit($start, $limit)->order('id desc')->select();
    //     $result['data'] = $list;
    //     return json($result);
    // }
    /**
     * 提现列表
     */
    public function transferList()
    {
        $page = $this->request->param("page") ? $this->request->param("page") : 1;
        $page = intval($page);
        $limit = $this->request->param("limit") ? $this->request->param("limit") : 1;
        $limit = intval($limit);
        $start = $limit * ($page - 1);
        $where = [];
        // 搜索条件判断
        $s_link_name = $this->request->param("key");
        if ($s_link_name != "") {
            $where[] = [
                "username|account", "=", $s_link_name,
            ];
        }
        $searchType = $this->request->param("type");
        if ($searchType != 'all' && $searchType != '') {
            $where[] = [
                'transfer_status', '=', $searchType
            ];
        }
        // 搜索条件判断结束
        $result['code'] = 0;
        $result['msg'] = '';
        $result['count'] = Transfer::count();
        $list = Transfer::where($where)->limit($start, $limit)->order('id desc')->select();
        $success_num = Transfer::where($where)->where('transfer_status', 2)->sum('price');
        $foot_num = Transfer::where($where)->where('transfer_status', 1)->sum('price');
        $result['data'] = $list;
        $result['success_num'] = $success_num;
        $result['foot_num'] = $foot_num;
        return json($result);
    }

    /**
     * 提现审核
     */
    public function transferCheck()
    {
        $id = $this->request->param('id');
        $status = $this->request->param('type');
        $data = [
            'transfer_status' => $status === 'success' ? 2 : 3,
            'send_time' => date('Y-m-d H:i:s'),
        ];
        $ret = Transfer::update($data, ['id' => $id]);
        if ($ret) {
            return json(['code' => 200, 'msg' => '处理成功']);
        }
        return json(['code' => -1, 'msg' => '处理失败']);
    }

    /**
     * 批量提现审核
     */
    public function transferBatchCheck()
    {
        $ids = $this->request->param('ids');
        $ids = explode(',', $ids);
        $status = $this->request->param('type');
        $data = [
            'transfer_status' => $status === 'success' ? 2 : 3,
            'send_time' => date('Y-m-d H:i:s'),
        ];
        foreach ($ids as $v) {
            Transfer::update($data, ['id' => $v]);
        }


        return json(['code' => 200, 'msg' => '处理成功']);

    }

    /**
     * 提现删除
     */
    public function transferDel()
    {
        $id = $this->request->param("id");
        if (empty($id)) {
            $idsTxt = $this->request->param('ids');
            $ret = Transfer::dels($idsTxt);
            if ($ret) {
                return json(['code' => 200, 'msg' => '删除成功']);
            }
            return json(['code' => -1, 'msg' => '删除失败']);
        } else {
            $ret = Transfer::del($id);
            if ($ret) {
                return json(['code' => 200, 'msg' => '删除成功']);
            }
            return json(['code' => -1, 'msg' => '删除失败']);
        }
    }

    /**
     * 提现备注设置
     */
    public function transferRemark()
    {
        $id = $this->request->param('id');
        $uid = $this->request->param('uid');
        $remark = $this->request->param('remarks');
        $ret = Transfer::update(['remarks' => $remark], ['id' => $id]);
        if ($ret) {
            // 为用户设置
            User::update(['remarks' => $remark], ['id' => $uid]);
            return json(['code' => 200, 'msg' => '备注成功']);
        }
        return json(['code' => -1, 'msg' => '备注失败']);
    }

    /**
     * 任务数据
     */
    public function task()
    {
        return view();
    }

    /**
     * 任务列表
     */
    public function taskList()
    {
        $page = $this->request->param("page") ? $this->request->param("page") : 1;
        $page = intval($page);
        $limit = $this->request->param("limit") ? $this->request->param("limit") : 1;
        $limit = intval($limit);
        $start = $limit * ($page - 1);
        $where = [];
        // 搜索条件判断结束
        $result['code'] = 0;
        $result['msg'] = '';
        $result['count'] = Task::count();
        $list = Task::where($where)->limit($start, $limit)->order('id desc')->select();
        $result['data'] = $list;
        return json($result);
    }

    /**
     * 任务添加
     */
    public function taskAdd()
    {
        $data = $this->request->param('task_data');
        $ret = Task::create(['task_data' => $data]);
        if ($ret) {
            return json(['code' => 200, 'msg' => '添加成功']);
        }
        return json(['code' => -1, 'msg' => '添加失败']);
    }

    /**
     * 任务编辑
     */
    public function taskEdit()
    {
        $id = $this->request->param('id');
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $ret = Task::update($data, ['id' => $id]);
            if ($ret) {
                return json(['code' => 200, 'msg' => '修改成功']);
            }
            return json(['code' => -1, 'msg' => '修改失败']);
        }
    }

    /**
     * 任务删除
     */
    public function taskDel()
    {
        $id = $this->request->param("id");
        if (empty($id)) {
            $idsTxt = $this->request->param('ids');
            $ret = Task::dels($idsTxt);
            if ($ret) {
                return json(['code' => 200, 'msg' => '删除成功']);
            }
            return json(['code' => -1, 'msg' => '删除失败']);
        } else {
            $ret = Task::del($id);
            if ($ret) {
                return json(['code' => 200, 'msg' => '删除成功']);
            }
            return json(['code' => -1, 'msg' => '删除失败']);
        }
    }

    /**
     * 邀请记录列表
     */
    public function invite()
    {
        return view();
    }

    /**
     * 邀请列表
     */
    public function inviteList()
    {
        $page = $this->request->param("page") ? $this->request->param("page") : 1;
        $page = intval($page);
        $limit = $this->request->param("limit") ? $this->request->param("limit") : 1;
        $limit = intval($limit);
        $start = $limit * ($page - 1);
        $where = [];
        // 搜索条件判断结束
        $result['code'] = 0;
        $result['msg'] = '';
        $result['count'] = Invite::count();
        $list = Invite::where($where)->limit($start, $limit)->order('id desc')->select();
        $result['data'] = $list;
        return json($result);
    }

    /**
     * 邀请删除
     */
    public function inviteDel()
    {
        $id = $this->request->param("id");
        if (empty($id)) {
            $idsTxt = $this->request->param('ids');
            $ret = Invite::dels($idsTxt);
            if ($ret) {
                return json(['code' => 200, 'msg' => '删除成功']);
            }
            return json(['code' => -1, 'msg' => '删除失败']);
        } else {
            $ret = Invite::del($id);
            if ($ret) {
                return json(['code' => 200, 'msg' => '删除成功']);
            }
            return json(['code' => -1, 'msg' => '删除失败']);
        }
    }

    /**
     * 公告页面
     */
    public function notice()
    {
        $info = Db::name('notice')->where('id', 1)->find();
        View::assign('info', $info);
        return View::fetch();
//        return view();
    }

    /**
     * 公告列表
     */
    public function noticeList()
    {
//        $page = $this->request->param("page") ? $this->request->param("page") : 1;
//        $page = intval($page);
//        $limit = $this->request->param("limit") ? $this->request->param("limit") : 1;
//        $limit = intval($limit);
//        $start = $limit * ($page - 1);
//        $where = [];
//        // 搜索条件判断结束
//        $result['code'] = 0;
//        $result['msg'] = '';
//        $result['count'] = Notice::count();
//        $list = Notice::where($where)->limit($start, $limit)->order('id desc')->select();
//        $result['data'] = $list;

        $info = Db::name('notice')->where('id', 2)->find();
        View::assign('info', $info);
        return View::fetch();

    }

    /**
     * 公告添加
     */
    public function noticeAdd()
    {
        $data = $this->request->param('content');
        $ret = Notice::create(['content' => $data]);
        if ($ret) {
            return json(['code' => 200, 'msg' => '添加成功']);
        }
        return json(['code' => -1, 'msg' => '添加失败']);
    }

    /**
     * 公告编辑
     */
    public function noticeEdit()
    {
        $id = $this->request->param('id');
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $ret = Notice::update($data, ['id' => 2]);
            if ($ret) {
                return json(['code' => 200, 'msg' => '修改成功']);
            }
            return json(['code' => -1, 'msg' => '修改失败']);
        }
    }

    /**
     * 公告删除
     */
    public function noticeDel()
    {
        $id = $this->request->param("id");
        if (empty($id)) {
            $idsTxt = $this->request->param('ids');
            $ret = Notice::dels($idsTxt);
            if ($ret) {
                return json(['code' => 200, 'msg' => '删除成功']);
            }
            return json(['code' => -1, 'msg' => '删除失败']);
        } else {
            $ret = Notice::del($id);
            if ($ret) {
                return json(['code' => 200, 'msg' => '删除成功']);
            }
            return json(['code' => -1, 'msg' => '删除失败']);
        }
    }


    /**
     * 收益设置
     */
//    public function profit()
//    {
//        if ($this->request->isPost()) {
//            $data = $this->request->param();
//            $ret = Profit::update($data, ['id' => 1]);
//            if ($ret) {
//                return json(['code' => 200, 'msg' => '修改成功']);
//            }
//            return json(['code' => -1, 'msg' => '修改失败']);
//        }
//        $info = Profit::where('id', 1)->find();
//        View::assign('info', $info);
//        return view();
//    }


    /**
     * 收益列表
     */
    public function profit()
    {
        return view();
    }

    /**
     * 收益列表
     */
    public function profitList()
    {
        $page = $this->request->param("page") ? $this->request->param("page") : 1;
        $page = intval($page);
        $limit = $this->request->param("limit") ? $this->request->param("limit") : 1;
        $limit = intval($limit);
        $start = $limit * ($page - 1);
        $where = [];
        // 搜索条件判断结束
        $result['code'] = 0;
        $result['msg'] = '';
        $result['count'] = Profit::count();
        $list = Profit::where($where)->limit($start, $limit)->order('id desc')->select();
        $result['data'] = $list;
        return json($result);
    }

    /**
     * 收益添加
     */
    public function profitAdd()
    {
        $data = $this->request->param();
        $ret = Profit::create($data);
        if ($ret) {
            return json(['code' => 200, 'msg' => '添加成功']);
        }
        return json(['code' => -1, 'msg' => '添加失败']);
    }

    /**
     * 收益编辑
     */
    public function profitEdit()
    {
        $id = $this->request->param('id');
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $ret = Profit::update($data, ['id' => $id]);
            if ($ret) {
                return json(['code' => 200, 'msg' => '修改成功']);
            }
            return json(['code' => -1, 'msg' => '修改失败']);
        }
    }

    /**
     * 收益删除
     */
    public function profitDel()
    {
        $id = $this->request->param("id");
        if (empty($id)) {
            $idsTxt = $this->request->param('ids');
            $ret = Profit::where('id','in',$idsTxt)->delete();
            if ($ret) {
                return json(['code' => 200, 'msg' => '删除成功']);
            }
            return json(['code' => -1, 'msg' => '删除失败']);
        } else {
            $ret = Profit::where('id',$id)->delete();
            if ($ret) {
                return json(['code' => 200, 'msg' => '删除成功']);
            }
            return json(['code' => -1, 'msg' => '删除失败']);
        }
    }


    /**
     * 修改密码
     */
    public function password()
    {
        if ($this->request->isPost()) {
            $password = $this->request->param('oldPsw');
            $newPassword = $this->request->param('newPsw');
            $rePassword = $this->request->param('rePsw');
            if ($newPassword != $rePassword) {
                return json(['code' => -1, 'msg' => '两次密码不一致']);
            }
            $admin = Session::get('admin');
            $adminInfo = Admin::where('id', $admin['id'])->find();
            if ($adminInfo['password'] != md5($password)) {
                return json(['code' => -1, 'msg' => '原密码错误']);
            }
            $ret = Admin::update(['password' => md5($newPassword)], ['id' => $admin['id']]);
            if ($ret) {
                return json(['code' => 200, 'msg' => '修改成功']);
            }
            return json(['code' => -1, 'msg' => '修改失败']);
        }
        return view();
    }

    public function out()
    {
        Session::delete('admin');
        return redirect('admin/index/index');

    }

    /**
     * 配置
     */
    public function config()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $ret = Config::where('id', 1)->update($data);
            if ($ret) {
                return json(['code' => 200, 'msg' => '修改成功']);
            }
            return json(['code' => -1, 'msg' => '修改失败']);
        }
        $info = Config::where('id', 1)->find();
        View::assign('info', $info);
        return view();
    }

    /**
     * 提现列表
     */
    public function transferPrice()
    {
        return view();
    }

    /**
     * 提现列表接口
     */
    public function transferPriceList()
    {
        $page = $this->request->param("page") ? $this->request->param("page") : 1;
        $page = intval($page);
        $limit = $this->request->param("limit") ? $this->request->param("limit") : 1;
        $limit = intval($limit);
        $start = $limit * ($page - 1);
        $where = [];
        // 搜索条件判断结束
        $result['code'] = 0;
        $result['msg'] = '';
        $result['count'] = TransferList::count();
        $list = TransferList::where($where)->limit($start, $limit)->select();
        $result['data'] = $list;
        return json($result);
    }

    /**
     * 添加提现
     */
    public function transferPriceAdd()
    {
        $data = $this->request->param();
        $ret = TransferList::create($data);
        if ($ret) {
            return json(['code' => 200, 'msg' => '添加成功']);
        }
        return json(['code' => -1, 'msg' => '添加失败']);
    }

    /**
     * 提现编辑
     */
    public function transferPriceEdit()
    {
        $id = $this->request->param('id');
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $ret = TransferList::update($data, ['id' => $id]);
            if ($ret) {
                return json(['code' => 200, 'msg' => '修改成功']);
            }
            return json(['code' => -1, 'msg' => '修改失败']);
        }
    }

    /**
     * 提现删除
     */
    public function transferPriceDel()
    {
        $id = $this->request->param("id");
        if (empty($id)) {
            $idsTxt = $this->request->param('ids');
            $ret = TransferList::dels($idsTxt);
            if ($ret) {
                return json(['code' => 200, 'msg' => '删除成功']);
            }
            return json(['code' => -1, 'msg' => '删除失败']);
        } else {
            $ret = TransferList::del($id);
            if ($ret) {
                return json(['code' => 200, 'msg' => '删除成功']);
            }
            return json(['code' => -1, 'msg' => '删除失败']);
        }
    }
















    /******************************* 以下是新增的**********************/


    /**
     * 话费管理
     */
    public function phonecharge()
    {
        return view();
    }

    /**
     * 话费列表
     */
    public function phonechargeList()
    {
        $page = $this->request->param("page") ? $this->request->param("page") : 1;
        $page = intval($page);
        $limit = $this->request->param("limit") ? $this->request->param("limit") : 1;
        $limit = intval($limit);
        $start = $limit * ($page - 1);
        $where = [];
        // 搜索条件判断
        $s_link_name = $this->request->param("key");
        if ($s_link_name != "") {
            $where[] = [
                "username|account", "=", $s_link_name,
            ];
        }
        $searchType = $this->request->param("type");
        if ($searchType != 'all' && $searchType != '') {
            $where[] = [
                'phonecharge_status', '=', $searchType
            ];
        }
        // 搜索条件判断结束
        $result['code'] = 0;
        $result['msg'] = '';
        $result['count'] = Phonecharge::count();
        $list = Phonecharge::where($where)->limit($start, $limit)->order('id desc')->select();
        $result['data'] = $list;
        return json($result);
    }

    /**
     * 话费审核
     */
    public function phonechargeCheck()
    {
        $id = $this->request->param('id');
        $status = $this->request->param('type');
        $data = [
            'phonecharge_status' => $status === 'success' ? 2 : 3,
            'send_time' => date('Y-m-d H:i:s'),
        ];
        $ret = Phonecharge::update($data, ['id' => $id]);
        if ($ret) {
            return json(['code' => 200, 'msg' => '处理成功']);
        }
        return json(['code' => -1, 'msg' => '处理失败']);
    }

    /**
     * 话费删除
     */
    public function phonechargeDel()
    {
        $id = $this->request->param("id");
        if (empty($id)) {
            $idsTxt = $this->request->param('ids');
            $ret = Phonecharge::dels($idsTxt);
            if ($ret) {
                return json(['code' => 200, 'msg' => '删除成功']);
            }
            return json(['code' => -1, 'msg' => '删除失败']);
        } else {
            $ret = Phonecharge::del($id);
            if ($ret) {
                return json(['code' => 200, 'msg' => '删除成功']);
            }
            return json(['code' => -1, 'msg' => '删除失败']);
        }
    }

    /**
     * 话费码备注设置
     */
    public function phonechargeRemark()
    {
        $id = $this->request->param('id');
        $uid = $this->request->param('uid');
        $remark = $this->request->param('remarks');
        $ret = Phonecharge::update(['remarks' => $remark], ['id' => $id]);
        if ($ret) {
            // 为用户设置
            User::update(['remarks' => $remark], ['id' => $uid]);
            return json(['code' => 200, 'msg' => '修改成功']);
        }
        return json(['code' => -1, 'msg' => '修改失败']);
    }


    /**
     * 话费卡列表
     */
    public function PhonechargePrice()
    {
        return view();
    }

    /**
     * 话费卡列表接口
     */
    public function PhonechargePriceList()
    {
        $page = $this->request->param("page") ? $this->request->param("page") : 1;
        $page = intval($page);
        $limit = $this->request->param("limit") ? $this->request->param("limit") : 1;
        $limit = intval($limit);
        $start = $limit * ($page - 1);
        $where = [];
        // 搜索条件判断结束
        $result['code'] = 0;
        $result['msg'] = '';
        $result['count'] = PhonechargeList::count();
        $list = PhonechargeList::where($where)->limit($start, $limit)->select();
        $result['data'] = $list;
        return json($result);
    }

    /**
     * 添加话费卡
     */
    public function PhonechargePriceAdd()
    {
        $data = $this->request->param();
        $ret = PhonechargeList::create($data);
        if ($ret) {
            return json(['code' => 200, 'msg' => '添加成功']);
        }
        return json(['code' => -1, 'msg' => '添加失败']);
    }

    /**
     * 话费卡编辑
     */
    public function PhonechargePriceEdit()
    {
        $id = $this->request->param('id');
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $ret = PhonechargeList::update($data, ['id' => $id]);
            if ($ret) {
                return json(['code' => 200, 'msg' => '修改成功']);
            }
            return json(['code' => -1, 'msg' => '修改失败']);
        }
    }

    /**
     * 话费卡删除
     */
    public function PhonechargePriceDel()
    {
        $id = $this->request->param("id");
        if (empty($id)) {
            $idsTxt = $this->request->param('ids');
            $ret = PhonechargeList::dels($idsTxt);
            if ($ret) {
                return json(['code' => 200, 'msg' => '删除成功']);
            }
            return json(['code' => -1, 'msg' => '删除失败']);
        } else {
            $ret = PhonechargeList::del($id);
            if ($ret) {
                return json(['code' => 200, 'msg' => '删除成功']);
            }
            return json(['code' => -1, 'msg' => '删除失败']);
        }
    }


    /**
     * 版本设置
     */
    public function version()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $ret = Version::update($data, ['id' => 1]);
            if ($ret) {
                return json(['code' => 200, 'msg' => '修改成功']);
            }
            return json(['code' => -1, 'msg' => '修改失败']);
        }
        $info = Version::where('id', 1)->find();
        View::assign('info', $info);
        return view();
    }


}
